//
//  VKStudyCardController.m
//  V-Learn
//
//  Created by liubo on 2019/2/11.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "VKStudyCardController.h"
#import "VKStudyCardRuleController.h"

#import "HeadView.h"
#import "CollectionCell.h"
#import "VKRecordController.h"
#import "VKStudyDaCardController.h"
#import "VKDakaRecordModel.h"
#import "WKMonthliModel.h"
#import "WKQingjiaModel.h"

#import "VKRecordNiuWaCell.h"
#import "VKServerXYController.h"
#import "DakaguizeViewController.h"
#import "WKDakaImageTextVC.h"
#import "VKRecordDetailVC.h"
#define kWidth [UIScreen mainScreen].bounds.size.width
#define kHeight [UIScreen mainScreen].bounds.size.height
#define kDay 24*60*60

/**

 */
@interface VKStudyCardController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *numberCellArray; /**cell的个数*/
@property (nonatomic, strong) NSMutableArray *selectedCellColorMArray; /**储存选中cell的的颜色*/
@property (nonatomic, strong) NSString *dateStr; /**今天的日期*/
@property (nonatomic, assign) NSInteger year;
@property (nonatomic, assign) NSInteger month;
@property (nonatomic, assign) NSInteger day;
@property (nonatomic, strong) UIImageView *imageV;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UILabel *riliLabel;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) NSMutableArray *nextPageDataArray;/**数据用作跳转使用*/

@property (nonatomic, strong) VKDakaRecordModel *model;
@property (nonatomic, assign) BOOL isSelectDate;

@property (nonatomic, assign) NSInteger currentMonth;
@property (nonatomic, assign) NSInteger currentYear;

@property (nonatomic, assign) NSInteger currentMonth2;//左滑数据
@property (nonatomic, assign) NSInteger currentYear2;//左滑数据

@property (nonatomic, assign) NSInteger currentMonth3;//优化数据
@property (nonatomic, assign) NSInteger currentYear3;//优化数据

@property (nonatomic, strong) NSArray *shoppingArray;/**用来判断有没有买过课程*/
@property (nonatomic, assign) NSInteger isPayCourse;/**是否购买过课程包括课程、课程包 1 购买  0 未购买*/

@property (nonatomic, strong) UILabel *qingjiatypeLab;
@property (nonatomic, strong) UILabel *qingjiatypeLab2;
@property (nonatomic, strong) UILabel *startTimeLab;
@property (nonatomic, strong) UILabel *startTimeLab2;
@property (nonatomic, strong) UILabel *endTimeLab;
@property (nonatomic, strong) UILabel *endTimeLab2;
@property (nonatomic, strong) UILabel *timeLenthLab;
@property (nonatomic, strong) UILabel *timeLenthLab2;
@property (nonatomic, strong) UILabel *reasonLab;
@property (nonatomic, strong) UILabel *reasonLab2;
@property (nonatomic, strong) UIView *footer;//底部视图
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIButton *jiluBtn;
@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, strong) UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *sourceArray;
@property(nonatomic,strong)NSIndexPath *indexpath;
@property(nonatomic,strong)UIView *showLineView;
@property(nonatomic,strong)UIView *showLineView2;
@end

@implementation VKStudyCardController
- (UIView *)showLineView{
    if (!_showLineView) {
        _showLineView = [UIView new];
        _showLineView.backgroundColor = [UIColor cyanColor];
    }
    return _showLineView;
}
- (UIView *)showLineView2{
    if (!_showLineView2) {
        _showLineView2 = [UIView new];
        _showLineView2.backgroundColor = [UIColor cyanColor];
    }
    return _showLineView2;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LBNAVBAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-LBNAVBAR_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
    }
    return _tableView;
}
-(NSMutableArray *)sourceArray{
    if (_sourceArray == nil) {
        _sourceArray = [[NSMutableArray alloc]init];
    }
    return _sourceArray;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.sourceArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    VKRecordNiuWaCell *cell = [VKRecordNiuWaCell cellWithTableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.followButton.layer.cornerRadius = 12;
    cell.followButton.layer.masksToBounds = YES;
    cell.followButton.layer.borderWidth = 1;
    cell.followButton.layer.borderColor = rgb(254,75,42).CGColor;
    cell.followButton.titleLabel.font = LBFont(12*kScaleFit);
    [cell.followButton setTitle:@"删除" forState:UIControlStateNormal];
    [cell.followButton setTitleColor:rgb(254,75,42) forState:UIControlStateNormal];
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    cell.followButton.tag = indexPath.section + 8818;
    [cell.followButton addTarget:self action:@selector(deleteBtn:) forControlEvents:UIControlEventTouchUpInside];
    cell.model = self.sourceArray[indexPath.row];
    cell.zanButton.tag = indexPath.section;
    cell.zanButton.hidden = YES;
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 435;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WKHotmenModel *model = self.sourceArray[indexPath.row];
    if ([model.fileType isEqualToString:@"2"]) {
        WKDakaImageTextVC *imagetextVC = [WKDakaImageTextVC new];
        imagetextVC.model = model;
        [self.navigationController pushViewController:imagetextVC animated:YES];
    }else{//视频
        VKRecordDetailVC *detailVC = [VKRecordDetailVC new];
        detailVC.model = model;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

// 删除
- (void)deleteBtn:(UIButton *)sender{
//    NSLog(@"%ld",sender.tag);
    
    WKHotmenModel *model = self.sourceArray[sender.tag - 8818];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    NSMutableDictionary *dic = @{@"token":[UserModel getUserModel].token,@"clockId":model.clockId}.mutableCopy;
    VKWeakSelf(self)
    
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKStudyMyDeleteClock withPostParams:dic.mutableCopy withBlock:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        if ([result[@"code"]integerValue] == 200) {
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
            
            //刷新数据
            [self requesDakaStatus:self.model];
        }
        [weakself.tableView reloadData];
        
    }];
}

// 集合视图的创建
- (void)createCollectionView
{
    UIImageView *imageV = [[UIImageView alloc]init];
    _imageV = imageV;
    //testbg
    imageV.image = [UIImage imageNamed:@"daka_bg"];//vkbg-calendar
    //    [scrollView addSubview:imageV];
    imageV.userInteractionEnabled = YES;
    imageV.frame = CGRectMake(10*ScaleX,  25*ScaleX, SCREEN_WIDTH-20*ScaleX, (SCREEN_WIDTH - 24*ScaleX - (5*8)*ScaleX)/7 * 6*ScaleX + 196*ScaleX);
    //    [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.mas_equalTo(LBNAVBAR_HEIGHT + 30);
    //        make.left.equalTo(@10);
    //        make.right.mas_equalTo(-10);
    //        make.height.equalTo((kWidth - 24 - 5*8)/7 * 6 + 196);
    //    }];
    
//    UIView *lineView = [UIView new];
//    lineView.backgroundColor = [UIColor orangeColor];
//    lineView.layer.cornerRadius = 0.5;
//    lineView.layer.masksToBounds = YES;
//    [imageV addSubview:lineView];
//    [lineView makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(2);
//        make.right.mas_equalTo(-2);
//        make.height.mas_equalTo(1*ScaleX);
//
//        if (IS_IPHONE_Xs_Max) {
//            make.top.mas_equalTo(115*ScaleX);
//        }else{
//            make.top.mas_equalTo(105*ScaleX);
//        }
//    }];
    
    UICollectionViewFlowLayout *viewFL = [[UICollectionViewFlowLayout alloc]init];
    viewFL.itemSize = CGSizeMake((SCREEN_WIDTH-20*ScaleX - 24 - (5*8)*ScaleX)/7, (SCREEN_WIDTH-20*ScaleX - 24 - (5*8)*ScaleX)/7);
    viewFL.minimumLineSpacing = 5*ScaleX;
    viewFL.minimumInteritemSpacing = 5*ScaleX;
    viewFL.sectionInset = UIEdgeInsetsMake(5*ScaleX, 5*ScaleX, 5*ScaleX, 5*ScaleX);
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(2, LBNAVBAR_HEIGHT, [UIScreen cz_screenWidth] - 24*ScaleX, (kWidth - 24*ScaleX - (5*8)*ScaleX)/7 * 6*ScaleX + 90*ScaleX) collectionViewLayout:viewFL];
    [_collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"item"];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [imageV addSubview:_collectionView];
    
    UIView *headerView = [UIView new];
    headerView.frame =  CGRectMake(0, 0, ScreenW, (SCREEN_WIDTH - 24*ScaleX - (5*8)*ScaleX)/7 * 6*ScaleX + 196*ScaleX+138*ScaleX);
    headerView.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:imageV];
    
    CGFloat H = (SCREEN_WIDTH - 24*ScaleX - (5*8)*ScaleX)/7 * 6*ScaleX + 196*ScaleX;
    UIButton *jiluBtn = [[UIButton alloc]init];
    self.jiluBtn = jiluBtn;
    [jiluBtn setImage:[UIImage imageNamed:@"vkbutton-blue"] forState:UIControlStateNormal];
    jiluBtn.highlighted = NO;
    [headerView addSubview:jiluBtn];
    [jiluBtn addTarget:self action:@selector(jiluBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [jiluBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@15);
        make.width.equalTo(@176);
        make.height.equalTo(@54);
        make.top.equalTo(@(30+H));
    }];
    
    UILabel *jiluLabel = [[UILabel alloc]init];
    jiluLabel.text = @"我的记录";
    jiluLabel.font = [UIFont systemFontOfSize:20];
    [jiluBtn addSubview:jiluLabel];
    jiluLabel.textColor = [UIColor whiteColor];
    [jiluLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(jiluBtn).offset(15);
        make.centerX.equalTo(jiluBtn);
        make.centerY.equalTo(jiluBtn);
    }];
    
    
    UIButton *cardBtn = [[UIButton alloc]init];
    [cardBtn setImage:[UIImage imageNamed:@"vkbutton-orange"] forState:UIControlStateNormal];
    [headerView addSubview:cardBtn];
    
    //    cardBtn.frame = CGRectMake(ScreenW/2, 25, 176, 54);
    [cardBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.width.equalTo(@176);
        make.height.equalTo(@54);
        make.top.equalTo(@(30+H));
    }];
    [cardBtn addTarget:self action:@selector(cardBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UILabel *cardLabel = [[UILabel alloc]init];
    //    cardLabel.frame = cardBtn.frame;
    cardLabel.text = @"打卡";
    cardLabel.textColor = [UIColor whiteColor];
    [cardBtn addSubview:cardLabel];
    cardLabel.font = [UIFont systemFontOfSize:20*ScaleX];
    [cardLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(cardBtn).offset(15);
        make.centerX.equalTo(cardBtn);
        make.centerY.equalTo(cardBtn);
    }];
    self.tableView.tableHeaderView = headerView;
    
    
    [_collectionView registerClass:[HeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    
    UIView *bottomView = [UIView new];
    self.bottomView = bottomView;
    bottomView.backgroundColor = [UIColor whiteColor];
    bottomView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 138);
    bottomView.hidden = YES;
    
    self.tableView.tableFooterView = bottomView;
    [self.view addSubview:self.tableView];
    if (@available(iOS 11.0,*)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    
    //请假原因
    [bottomView addSubview:self.qingjiatypeLab];
    
    [self.qingjiatypeLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(15);
    }];
    
    [bottomView addSubview:self.qingjiatypeLab2];
    self.qingjiatypeLab2.text = @"婚假";
    self.qingjiatypeLab2.numberOfLines = 2;
    [self.qingjiatypeLab2 makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.qingjiatypeLab.mas_right).mas_equalTo(25);
        make.top.mas_equalTo(15);
        make.right.mas_equalTo(-15);
    }];
    
    //开始时间
    [bottomView addSubview:self.startTimeLab];
    [self.startTimeLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(self.qingjiatypeLab2.mas_bottom).mas_equalTo(5);
    }];
    
    [bottomView addSubview:self.startTimeLab2];
    self.startTimeLab2.text = @"2019-2-3";
    [self.startTimeLab2 makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.startTimeLab.mas_right).mas_equalTo(25);
        make.top.mas_equalTo(self.qingjiatypeLab2.mas_bottom).mas_equalTo(5);
    }];
    
    //结束时间
    [bottomView addSubview:self.endTimeLab];
    [self.endTimeLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(self.startTimeLab.mas_bottom).mas_equalTo(5);
    }];
    
    [bottomView addSubview:self.endTimeLab2];
    self.endTimeLab2.text = @"2019-2-4";
    [self.endTimeLab2 makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.endTimeLab.mas_right).mas_equalTo(25);
        make.top.mas_equalTo(self.startTimeLab.mas_bottom).mas_equalTo(5);
    }];
    
    //时长
//    [bottomView addSubview:self.timeLenthLab];
//    [self.timeLenthLab makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(10);
//        make.top.mas_equalTo(self.endTimeLab.mas_bottom).mas_equalTo(5);
//    }];
    
//    [bottomView addSubview:self.timeLenthLab2];
//    self.timeLenthLab2.text = @"请了一天的假";
//    [self.timeLenthLab2 makeConstraints:^(MASConstraintMaker *make) {
////        make.left.mas_equalTo(self.endTimeLab2.mas_left).mas_equalTo(0);
////        make.top.mas_equalTo(self.endTimeLab.mas_bottom).mas_equalTo(5);
//        make.left.mas_equalTo(10);
//        make.top.mas_equalTo(self.endTimeLab.mas_bottom).mas_equalTo(5);
//    }];
    
    //时长
    [bottomView addSubview:self.reasonLab];
    [self.reasonLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(self.endTimeLab2.mas_bottom).mas_equalTo(5);
    }];
    
    [bottomView addSubview:self.reasonLab2];
    self.reasonLab2.text = @"用心对待每一天";
    self.reasonLab2.numberOfLines = 0;
    [self.reasonLab2 makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.reasonLab.mas_right).mas_equalTo(25);
        make.top.mas_equalTo(self.endTimeLab2.mas_bottom).mas_equalTo(5);
        make.right.mas_equalTo(-15);
    }];
    
}
- (UILabel *)qingjiatypeLab{
    if (!_qingjiatypeLab) {
        _qingjiatypeLab = [UILabel labelWithText:@"请假类型" andTextColor:rgb(102,102,102) andName:nil andFontSize:14];
    }
    return _qingjiatypeLab;
}
- (UILabel *)reasonLab2{
    if (!_reasonLab2) {
        _reasonLab2 = [UILabel labelWithText:@"" andTextColor:rgb(51,51,51) andName:nil andFontSize:14];
    }
    return _reasonLab2;
}
- (UILabel *)reasonLab{
    if (!_reasonLab) {
        _reasonLab = [UILabel labelWithText:@"请假原因" andTextColor:rgb(102,102,102) andName:nil andFontSize:14];
    }
    return _reasonLab;
}
- (UILabel *)timeLenthLab2{
    if (!_timeLenthLab2) {
        _timeLenthLab2 = [UILabel labelWithText:@"" andTextColor:rgb(51,51,51) andName:nil andFontSize:14];
    }
    return _timeLenthLab2;
}
- (UILabel *)timeLenthLab{
    if (!_timeLenthLab) {
        _timeLenthLab = [UILabel labelWithText:@"时长" andTextColor:rgb(102,102,102) andName:nil andFontSize:14];
    }
    return _timeLenthLab;
}
- (UILabel *)endTimeLab2{
    if (!_endTimeLab2) {
        _endTimeLab2 = [UILabel labelWithText:@"" andTextColor:rgb(51,51,51) andName:nil andFontSize:14];
    }
    return _endTimeLab2;
}
- (UILabel *)endTimeLab{
    if (!_endTimeLab) {
        _endTimeLab = [UILabel labelWithText:@"结束时间" andTextColor:rgb(102,102,102) andName:nil andFontSize:14];
    }
    return _endTimeLab;
}

- (UILabel *)qingjiatypeLab2{
    if (!_qingjiatypeLab2) {
        _qingjiatypeLab2 = [UILabel labelWithText:@"" andTextColor:rgb(51,51,51) andName:nil andFontSize:14];
    }
    return _qingjiatypeLab2;
}
- (UILabel *)startTimeLab{
    if (!_startTimeLab) {
        _startTimeLab = [UILabel labelWithText:@"开始时间" andTextColor:rgb(102,102,102) andName:nil andFontSize:14];
    }
    return _startTimeLab;
}
- (UILabel *)startTimeLab2{
    if (!_startTimeLab2) {
        _startTimeLab2 = [UILabel labelWithText:@"" andTextColor:rgb(51,51,51) andName:nil andFontSize:14];
    }
    return _startTimeLab2;
}

- (void)requesDakaStatus:(VKDakaRecordModel*)model{
    
    __weak typeof(self)weakSelf = self;
    if ([model.calendarType isEqualToString:@"1"]) {//1 是请假  ，其他的显示都是打卡记录
        
        [WYHXNetWorkManager get:WKQueryAskLeaveByDay_WKURL params:@{@"token":[UserModel getUserModel].token,@"date":model.calendarDate} completionHandler:^(id responseObj, NSError *error) {
            NSString *code = responseObj[@"code"];
            if ([code integerValue]==200) {
                [self showSubView];
                WKQingjiaModel *qingjiaModel = [WKQingjiaModel mj_objectWithKeyValues:responseObj[@"data"]];
                self.qingjiatypeLab2.text = qingjiaModel.leaveType;
                self.startTimeLab2.text = qingjiaModel.startDate;
                self.endTimeLab2.text = qingjiaModel.endDate;
                [NSString stringWithFormat:@"共%@天",qingjiaModel.leaveDuration];
                self.reasonLab2.text = qingjiaModel.leaveInfo;
                [self.sourceArray removeAllObjects];
                self.bottomView.hidden = NO;
                CGSize titleSize = [qingjiaModel.leaveInfo sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(ScreenW-98-15, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
                
                CGSize titleSize2 = [qingjiaModel.leaveType sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(ScreenW-98-15, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
                self.bottomView.frame = CGRectMake(0, 0, ScreenW, 138+titleSize.height+titleSize2.height);
                [self.tableView reloadData];
                
            }
            
        }];
    }else{
        NSString *dateString =  model.calendarDate;
        NSString *string =model.calendarDate;
        
        NSArray *array = [string componentsSeparatedByString:@"-"]; //从字符A中分隔成2个元素的数组
//        NSLog(@"%@",array);
        NSString *str = array[0];
        NSString *str2 = array[1];
        NSString *str3 = array[2];
        if (str2.length==1) {
            str2 = [NSString stringWithFormat:@"0%@",str2];
        }
        if (str3.length==1) {
            str3 = [NSString stringWithFormat:@"0%@",str3];
        }
        NSString *dataStr = [NSString stringWithFormat:@"%@-%@-%@",str,str2,str3];
//        NSLog(@"%@",dataStr);
        [WYHXNetWorkManager get:WKQueryClockRecordByDateDay_WKURL params:@{@"token":[UserModel getUserModel].token,@"date":dataStr} completionHandler:^(id responseObj, NSError *error) {
            
            NSString *code = responseObj[@"code"];
            if ([code integerValue]==200) {
                self.sourceArray = [NSMutableArray array];
                for (NSDictionary *dic in responseObj[@"data"]) {
                    WKHotmenModel *model = [WKHotmenModel mj_objectWithKeyValues:dic];
                    [self.sourceArray addObject:model];
                }
                self.bottomView.hidden = YES;
                [self.tableView reloadData];
            }
            
        }];
    }
    
}
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
-(NSMutableArray *)numberCellArray
{
    if (!_numberCellArray)
    {
        _numberCellArray = [[NSMutableArray array]init];
    }
    return _numberCellArray;
}
-(NSMutableArray *)selectedCellColorMArray{
    
    if (!_selectedCellColorMArray) {
        
        _selectedCellColorMArray = [[NSMutableArray alloc]init];
    }
    return _selectedCellColorMArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"月历打卡";
    self.selectIndex = 0;
    // 右边按钮
    [self setupRightItem];
    
    [self createCollectionView];
    // 日历切换按钮
    [self setupRiliItem];
    [self createCellNumber:[NSDate date]];
    _year = [self year:[NSDate date]];
    _month = [self month:[NSDate date]];
    _day = 0;
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-M"];
    _dateStr = [formatter stringFromDate:date];

}
#pragma mark - 这里我修改了 为了打卡后展示最新的打卡状态
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //获取数据有没有买过课程
    [self requestDataMyShoppingCourese];
    //请求接口数据
    [self requestData];
}
- (void)requestDataMyShoppingCourese{
    
    NSString *token = [UserModel getUserModel].token;
    if (token) {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        
        [data setObject:token forKey:@"token"];
        [WYHXNetWorkManager get:WKQueryIsPayedCourse_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
            NSLog(@"%@",responseObj);
            NSString *code = responseObj[@"code"];
            if ([code integerValue]==200) {
                self.isPayCourse = [responseObj[@"data"] integerValue];
            }
            self.selectIndex = 0;
            [self.collectionView reloadData];
        }];
        
    }
    
}
- (void)requestData{
    NSString *token = [UserModel getUserModel].token;
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setObject:token forKey:@"token"];
    NSString *yearMonth = [NSString stringWithFormat:@"%ld-%ld",_year,_month];
    [data setObject:yearMonth forKey:@"yearMonth"];
    // 0 缺卡 1 请假 2 打卡 3 补卡  110是我补齐的
    [WYHXNetWorkManager get:WKgetClockCalendarDate_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
        NSLog(@"%@",responseObj);
        self.selectIndex =0;
        [self.dataArray removeAllObjects];
        [self.nextPageDataArray removeAllObjects];
        //        NSLog(@"%@%@",responseObj,error);
        NSString *code = responseObj[@"code"];
        NSDictionary *data = responseObj[@"data"];
        if ([code integerValue]==200) {
            self.isSelectDate = NO;
            self.nextPageDataArray = [VKDakaRecordModel mj_objectArrayWithKeyValuesArray:data[@"clockCalendarVOS"]];
            for (NSDictionary *dic in data[@"clockCalendarVOS"]) {
                [self.dataArray addObject:dic[@"calendarType"]];
            }
        }
//        NSLog(@"dataarray:%@",self.dataArray);
        [self.collectionView reloadData];
    }];
    
    
}
- (void)setupRiliItem{
    //self.navigationItem.title
    //    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"上一月" style:UIBarButtonItemStylePlain target:self action:@selector(lastMonth)];
    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"下一月" style:UIBarButtonItemStylePlain target:self action:@selector(nextMonth)];
    
    UIImageView *rightImage = [[UIImageView alloc]init];
    rightImage.userInteractionEnabled = YES;
    rightImage.image = [UIImage imageNamed:@"vkright1"];
    [_imageV addSubview:rightImage];
    [rightImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(_imageV).offset(-15);
        make.height.equalTo(@17);
        make.width.equalTo(@9);
        make.top.mas_equalTo(@40);
    }];
    
    UIButton *rightItem = [[UIButton alloc]init];
    [rightImage addSubview:rightItem];
    [rightItem mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(rightImage);
        make.height.width.equalTo(@25);
    }];
    [rightItem addTarget:self action:@selector(rightItemClick) forControlEvents:UIControlEventTouchUpInside];
    rightItem.backgroundColor = [UIColor clearColor];
    
    UILabel *riliLabel = [[UILabel alloc]init];
    riliLabel.text = [NSString stringWithFormat:@"%ld年%ld月",(long)[self year:[NSDate date]],[self month:[NSDate date]]];
    _riliLabel = riliLabel;
    [_imageV addSubview:riliLabel];
    [riliLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(rightItem.mas_left).offset(-15);
        make.centerY.equalTo(rightItem);
    }];
    
    
    
    UIButton *leftItem = [[UIButton alloc]init];
    [_imageV addSubview:leftItem];
    [leftItem mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(riliLabel.mas_left).offset(-15);
        make.centerY.equalTo(rightItem);
        make.height.width.equalTo(@25);
        
    }];
    [leftItem addTarget:self action:@selector(leftItemClick) forControlEvents:UIControlEventTouchUpInside];
    leftItem.backgroundColor = [UIColor clearColor];
    
    UIImageView *leftImage = [[UIImageView alloc]init];
    leftImage.userInteractionEnabled = NO;
    leftImage.image = [UIImage imageNamed:@"vkleft1"];
    [_imageV addSubview:leftImage];
    [leftImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(leftItem);
        make.height.equalTo(@17);
        make.width.equalTo(@9);
    }];

    
}
-(NSInteger)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
//    NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }else{
        return 0;
    }
    //NSLog(@"Both dates are the same")
    
}


- (void)cardBtnClick{
    
    
    if (self.isPayCourse==0) {
        [MBProgressHUD showSuccess:@"您还没有购买课程!" toView:self.view];
        return;
    }else{
        VKStudyDaCardController *daCard = [[VKStudyDaCardController alloc]init];
        //获取当前时间日期
        NSDate *date=[NSDate date];
        NSDateFormatter *format1=[[NSDateFormatter alloc] init];
        [format1 setDateFormat:@"yyyy-MM-dd"];
        NSString *dateStr;
        dateStr=[format1 stringFromDate:date];
        NSString *year = [dateStr substringToIndex:4];
        NSString *month = [dateStr substringWithRange:NSMakeRange(5, 2)];
//        NSLog(@"year=%ld,month=%ld",[year integerValue],[month integerValue]);
//        NSLog(@"year=%ld,month=%ld",self.currentYear,self.currentMonth);
        if ([year integerValue]==self.currentYear&&[month integerValue]==self.currentMonth) {
            
            if (self.isSelectDate) {//点击了日历表
                
                NSString *birthdayStr = self.model.calendarDate;
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd"];
                [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题
                NSDate *birthdayDate = [dateFormatter dateFromString:birthdayStr];
                
                NSInteger index = [self compareOneDay:date withAnotherDay:birthdayDate];
                

                if (index==-1) {
                    [MBProgressHUD showSuccess:@"打卡不能选择大于今天的日期" toView:self.view];
                    return;
                }else{
                    daCard.clockType = @"2";//self.model.calendarType;//
                    daCard.clockDate = self.model.calendarDate;//日期   默认日期是当期
                    [self.navigationController pushViewController:daCard animated:YES];
                }
            }else{
                
                if (self.currentYear2 == [year integerValue]&&self.currentMonth2<[month integerValue]) {
                    [MBProgressHUD showSuccess:@"只能在当月打卡" toView:self.view];
                    return;
                }
                
                if (self.currentYear3 == [year integerValue]&&self.currentMonth3>[month integerValue]) {
                    [MBProgressHUD showSuccess:@"只能在当月打卡" toView:self.view];
                    return;
                }
                daCard.clockType = @"2";//默认不点击是 打卡 2
                daCard.clockDate = dateStr;//日期   默认日期是当期
                [self.navigationController pushViewController:daCard animated:YES];
            }

        
        }else{
            [MBProgressHUD showSuccess:@"只能在当月打卡" toView:self.view];
            return;
        }
    }
    
    
}
- (void)jiluBtnClick{
    NSString *token = [UserModel getUserModel].token;
    
    if (token == nil) {
        LBLoginVC *loginVC = [[LBLoginVC alloc] init];
        loginVC.jumpType = @"1";
        [self.navigationController pushViewController:loginVC animated:YES];
        return;
    }
    [self.navigationController pushViewController:[[VKRecordController alloc]init] animated:YES];
}
- (void)leftItemClick{
    self.selectIndex = 0;
    
    [self lastMonth];
    
}
- (void)rightItemClick{
    self.selectIndex = 0;
    
    [self nextMonth];
}
// 右边Item
- (void)setupRightItem{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"打卡规则" forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 70, 30);
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button setTitleColor:[UIColor cz_colorWithRed:115 green:115 blue:115] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button] ;
    
    [button addTarget:self action:@selector(buttonItemClick:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonItemClick:(UIButton *)sender{
    
    DakaguizeViewController *xy = [[DakaguizeViewController alloc]init];
    xy.title = @"打卡规则";
    [self.navigationController pushViewController:xy animated:YES];
}

#pragma mark ---左右按钮的点击方法
- (void)lastMonth
{
    
    _month = _month - 1;
    _day = _day - 1;
    if (_month == 0)
    {
        _month = 12;
        _year = _year - 1;
    }
    _riliLabel.text = [NSString stringWithFormat:@"%ld年%ld月",_year,_month];
    self.currentMonth = _month;
    self.currentMonth2 = _month;
    self.currentYear = _year;
    self.currentYear2 = _year;
    NSDate *lastDate = [[NSDate date] dateByAddingTimeInterval:_day*kDay * [self totaldaysInMonth:[NSDate date]]];
    [self createCellNumber:lastDate];
    //请求接口数据
    [self requestData];
    //    [_collectionView reloadData];
    self.isSelectDate = NO;
}
- (void)nextMonth
{
    _month = _month + 1;
    _day = _day + 1;
    if (_month == 13)
    {
        _month = 1;
        _year = _year + 1;
    }
    _riliLabel.text = [NSString stringWithFormat:@"%ld年%ld月",(long)_year,_month];
    self.currentMonth = _month;
    self.currentYear = _year;
    
    self.currentMonth3 = _month;
    self.currentYear3 = _year;
    NSDate *nextDate = [[NSDate date] dateByAddingTimeInterval:_day*kDay * [self totaldaysInMonth:[NSDate date]]];
    [self createCellNumber:nextDate];
    //    [_collectionView reloadData];
    //请求接口数据
    [self requestData];
}

#pragma mark UICollectionView的代理方法
//分区
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//返回分区下，单元格的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.dataArray.count == 0) {
        return 0;
    }

    return self.numberCellArray.count;
}


//cell的编辑,定义item
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    //  从重用队列中取出注册的cell
    CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    if (!cell) {
        
        cell = [[CollectionCell alloc]init];
    }
    cell.backgroundColor = [UIColor clearColor];
    
    cell.lable.text = self.numberCellArray[indexPath.row];
    
    
    //            cell.backgroundColor = [UIColor orangeColor];
    
    
    NSString *str = self.numberCellArray[indexPath.row];
    if ([str isEqualToString:@""]) {
        cell.imageV.image = [UIImage imageNamed:@""];
        self.selectIndex ++;
    }else{
        
        // 0 缺卡 1 请假 2 打卡 3 补卡  110是我补齐的
        
        if ([self.dataArray[indexPath.row - self.selectIndex] integerValue] == 0) {
            cell.imageV.image = [UIImage imageNamed:@""];

        }else if ([self.dataArray[indexPath.row - self.selectIndex] integerValue] == 1){
            cell.imageV.image = [UIImage imageNamed:@""];
        }else if([self.dataArray[indexPath.row - self.selectIndex] integerValue] == 2){
            cell.imageV.image = [UIImage imageNamed:@"vkFootprint"];
        }else if([self.dataArray[indexPath.row - self.selectIndex] integerValue] == 3){
            cell.imageV.image = [UIImage imageNamed:@"vkFootprint"];
        }else{
            cell.imageV.image = [UIImage imageNamed:@""];
        }
    }
    if (indexPath.row < self.selectIndex) {
        
    }else{
        if (_indexpath.row == indexPath.row) {
            // 在这个地方
            
            
            cell.backgroundColor = [UIColor yellowColor];
            
        }
    }
    
    // 今天是否等于对应的日期
    if ([[NSString stringWithFormat:@"%ld-%ld",(long)_year,(long)_month] isEqualToString:_dateStr])
    {
        if ([self day:[NSDate date]] == [self.numberCellArray[indexPath.row] integerValue])
        {
            // 在这个地方
            
            cell.backgroundColor = [UIColor orangeColor];
        }
        
    }
    if (self.selectedCellColorMArray.count > 0) {
        
        
        
        if ([self.selectedCellColorMArray[indexPath.row] isEqualToString:@"1"]){
            
            cell.backgroundColor = [UIColor clearColor];
        }
    }
    return cell;
}
//定义头视图的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(kWidth - 24, 40);
}

//定义头视图的代理方法
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    HeadView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
    //   设置图视图背景色
    headView.backgroundColor = [UIColor clearColor];
    
    return headView;
}
// 点击cell的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row < self.selectIndex) {
        
    }else{
        //        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        //        cell.backgroundColor = [UIColor yellowColor];
        //
        _indexpath = indexPath;
        self.isSelectDate = YES;
        VKDakaRecordModel *model = self.nextPageDataArray[indexPath.row-(self.selectIndex)];
        self.model = model;
//        NSLog(@"%@,%ld",model.calendarDate,indexPath.row);
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        [self requesDakaStatus:model];
        self.selectIndex = 0;
        
        [self.collectionView reloadData];
    }
    
    
    //    [self.selectedCellColorMArray removeAllObjects];
    //    for (int i = 0; i < self.numberCellArray.count; i++) {
    //
    //        if (i == indexPath.row) {
    //
    //            [self.selectedCellColorMArray addObject:@"1"];
    //        }else{
    //
    //            [self.selectedCellColorMArray addObject:@"0"];
    //        }
    //    }
    //    [collectionView reloadData];
}

- (void)hienSubView{
    self.qingjiatypeLab.hidden = YES;
    self.qingjiatypeLab2.hidden = YES;
    self.startTimeLab.hidden = YES;
    self.startTimeLab2.hidden = YES;
    self.endTimeLab.hidden = YES;
    self.endTimeLab2.hidden = YES;
    self.timeLenthLab.hidden = YES;
    self.timeLenthLab2.hidden = YES;
    self.reasonLab.hidden = YES;
    self.reasonLab2.hidden = YES;
}
- (void)showSubView{
    self.qingjiatypeLab.hidden = NO;
    self.qingjiatypeLab2.hidden = NO;
    self.startTimeLab.hidden = NO;
    self.startTimeLab2.hidden = NO;
    self.endTimeLab.hidden = NO;
    self.endTimeLab2.hidden = NO;
    self.timeLenthLab.hidden = NO;
    self.timeLenthLab2.hidden = NO;
    self.reasonLab.hidden = NO;
    self.reasonLab2.hidden = NO;
}
#pragma mark --- 本类调用 ---
// 要创建的cell的个数
- (void)createCellNumber:(NSDate *)date
{
    [self.numberCellArray removeAllObjects];
    NSInteger days = [self totaldaysInMonth:date];
    NSDate *date1 = [date dateByAddingTimeInterval:-([self day:date] - 1)*kDay];
    NSInteger severalDayOfWeek = [self severalWeeks:date1];
    for (int i = 0; i < severalDayOfWeek - 1; i++)
    {
        [self.numberCellArray addObject:@""];
    }
    for (int i = 0; i < days; i++)
    {
        [self.numberCellArray addObject:[NSString stringWithFormat:@"%d",i+1]];
    }
    
    
}

// 今天是哪一天
- (NSInteger)day:(NSDate *)date
{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components day];
}
// 今天是周几
- (NSInteger)severalWeeks:(NSDate *)date
{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:date];
    return [components weekday];
}

// 本月是那一月
- (NSInteger)month:(NSDate *)date
{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    self.currentMonth = [components month];
    return [components month];
}
// 今年是那一年
- (NSInteger)year:(NSDate *)date
{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    self.currentYear = [components year];
    return [components year];
}
// 这个月共有几天
- (NSInteger)totaldaysInMonth:(NSDate *)date
{
    NSRange daysInLastMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return daysInLastMonth.length;
}

@end














